package user

import (
	"github.com/snowlyg/iris-admin/server/zap_server"
	"github.com/snowlyg/iris-admin/utils"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type PSysUser struct {
	gorm.Model
	BaseUser
	Password string `gorm:"type:varchar(250)" json:"password" validate:"required"`
	RoleIds  []uint `gorm:"-" json:"role_ids"`
}

type BaseUser struct {
	Username      string         `gorm:"index;not null; type:varchar(60)" json:"username" comment:"用户名"`
	OrgId         string         `gorm:"not null; type:varchar(512)" json:"orgId" comment:"部门id"`
	LockTime      utils.JsonTime `gorm:"type:datetime" json:"avatar" comment:"锁定时间"`
	LastLoginTime utils.JsonTime `gorm:"type:datetime" json:"lastLoginTime" comment:"上一次登录时间"`
	TryCount      uint           `gorm:"type:int" json:"tryCount" comment:"尝试次数"`
	LockFlag      uint           `gorm:"type:int" json:"lockFlag" comment:"锁定标识"`
	RealName      string         `gorm:"type:varchar(512)" json:"realName" comment:"名称"`
}

type Avatar struct {
	Avatar string `json:"avatar"`
}

// Create 添加
func (item *PSysUser) Create(db *gorm.DB) (uint, error) {
	err := db.Model(item).Create(item).Error
	if err != nil {
		zap_server.ZAPLOG.Error("添加失败", zap.String("(item *User) Create()", err.Error()))
		return item.ID, err
	}
	return item.ID, nil
}

// Update 更新
func (item *PSysUser) Update(db *gorm.DB, scopes ...func(db *gorm.DB) *gorm.DB) error {
	err := db.Model(item).Scopes(scopes...).Updates(item).Error
	if err != nil {
		zap_server.ZAPLOG.Error("更新失败", zap.String("(item *User) Update() ", err.Error()))
		return err
	}
	return nil
}

// Delete 删除
func (item *PSysUser) Delete(db *gorm.DB, scopes ...func(db *gorm.DB) *gorm.DB) error {
	err := db.Model(item).Unscoped().Scopes(scopes...).Delete(item).Error
	if err != nil {
		zap_server.ZAPLOG.Error("删除失败", zap.String("(item *User) Delete()", err.Error()))
		return err
	}
	return nil
}
